package utils;

import android.os.Parcel;
import android.os.Parcelable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadUtil implements Parcelable {
    public Call call;
    public DownloadUtil(String url)  {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        call = okHttpClient.newCall(request);
    }

    protected DownloadUtil(Parcel in) {
    }

    public static final Creator<DownloadUtil> CREATOR = new Creator<DownloadUtil>() {
        @Override
        public DownloadUtil createFromParcel(Parcel in) {
            return new DownloadUtil(in);
        }

        @Override
        public DownloadUtil[] newArray(int size) {
            return new DownloadUtil[size];
        }
    };

    /**
     * @param destFileDir  下载的文件储存目录
     * @param destFileName 下载文件名称
     * @param listener     下载监听
     */
    public void download(final String destFileDir, final String destFileName, final OnDownloadListener listener) {
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败监听回调
                listener.onDownloadFailed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                File dir = new File(destFileDir);
                MyUtil.showLog("dir",dir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, destFileName);
                MyUtil.showLog("exists:"+file.exists(),file);
                file.delete();
                MyUtil.showLog("destFileName",file);
                try {
                    is = response.body().byteStream();
                    MyUtil.showLog("is",is);
                    long total = response.body().contentLength();
                    MyUtil.showLog("total",total);
                    fos = new FileOutputStream(file);
                    MyUtil.showLog("fos",fos);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中更新进度条
                        listener.onDownloading(progress);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess(file);
                } catch (Exception e) {
                    listener.onDownloadFailed(e);
                } finally {
                    MyUtil.showLog("finally is",is);
                    MyUtil.showLog("finally fos",fos);
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
    }

    public interface OnDownloadListener {
        /**
         * @param file 下载成功后的文件
         */
        void onDownloadSuccess(File file);

        /**
         * @param progress 下载进度
         */
        void onDownloading(int progress);

        /**
         * @param e 下载异常信息
         */
        void onDownloadFailed(Exception e);
    }
}
